/*
 * Copyright (C) 2019-2020 Alibaba Group Holding Limited
 */

#include "genie_sal.h"
#include "genie_mesh_api.h"

#include "sensor_battery.h"
#include "sensor.h"

static battery_t battery;

static uint32_t battery_average_value(uint32_t new_value)
{
    uint8_t index = 0;
    uint32_t sum = 0;
    uint32_t min = SENSOR_BATTERY_VALID_MAX;
    uint32_t max = SENSOR_BATTERY_VALID_MIN;

    if (new_value >= SENSOR_BATTERY_VALID_MIN && new_value <= SENSOR_BATTERY_VALID_MAX)
    {
        battery.value[battery.count++] = new_value;
    }

    for (index = 0; index < SENSOR_BATTERY_SAVE_COUNT; index++)
    {
        sum += battery.value[index];
        if (min > battery.value[index])
        {
            min = battery.value[index];
        }
        if (max < battery.value[index])
        {
            max = battery.value[index];
        }
    }

    sum -= min;
    sum -= max;
    battery.count = battery.count % SENSOR_BATTERY_SAVE_COUNT;

    return sum / (SENSOR_BATTERY_SAVE_COUNT - 2);
}

int32_t sensor_get_battery_level(uint32_t *battery_level)
{
    int32_t ret = 0;
    uint32_t level = 0;

    //HAL_WAIT_FOREVER is not used in tg7100b
    ret = hal_adc_value_get(&battery.battery_check, (void *)&level, HAL_WAIT_FOREVER);
    if (ret != 0)
    {
        GENIE_LOG_ERR("read battery fail");
    }

    *battery_level = battery_average_value(level);

    return ret;
}

int32_t sensor_battery_init(void)
{
    int ret = -1;
    int index = 0;

    memset(&battery, 0, sizeof(battery_t));

    for (index = 0; index < SENSOR_BATTERY_SAVE_COUNT; index++)
    {
        battery.value[index] = SENSOR_BATTERY_DEFAULT_VALUE;
    }

    battery.battery_check.port = SENSOR_BATTERY_CHECK_PIN;
    battery.battery_check.config.sampling_cycle = SENSOR_BATTERY_CHECK_SAMPLE_RATE;

    if (battery.battery_check.port < 0)
    {
        GENIE_LOG_WARN("get adc channel fail");
        return -1;
    }

    ret = hal_adc_init(&battery.battery_check);
    if (ret != 0)
    {
        GENIE_LOG_ERR("battery init fail");
    }

    return ret;
}
